﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControls_CarbonFootprintQuestion_Transport_IntercityTrainTravel : CarbonExchange.WebControls.AuditQuestionSigleItemBase
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public override void DataBind()
    {
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("txt")))
            txt.Text = Answer.GetSetting<string>("txt");
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("ddl")))
            ddl.Text = Answer.GetSetting<string>("ddl");
        base.DataBind();
    }

    protected override bool SaveQuestion()
    {
        var completed = true;
        Answer.SetSetting<string>("txt", txt.Text);
        Answer.SetSetting<string>("ddl", ddl.Text);

        CarbonExchange.Bll.AmeeProfileItemFactory profileFactory = new CarbonExchange.Bll.AmeeProfileItemFactory();
        CarbonExchange.Bll.AmeeDataCatagoryFactory dataFactory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();

        var tmpProfileItem = EnsureProfileItem(Answer.SingleItem.Name, profileFactory, dataFactory, "transport/train/generic", "type=national");

        var save = string.IsNullOrEmpty(tmpProfileItem.Id);

        decimal distance = 0;
        try
        {
            distance = decimal.Parse(txt.Text);
        }
        catch (FormatException)
        {
        }

        if (ddl.Text == "miles")
        {
            distance = distance * 1.609344m;
        }

        if (tmpProfileItem.GetValue<decimal>("distanceKmPerMonth") != distance)
        {
            tmpProfileItem.SetValue<decimal>("distanceKmPerMonth", distance);
            save = true;
        }

        if (save)
        {
            profileFactory.Save(tmpProfileItem);
        }

        Answer.SetSingleItem(tmpProfileItem);

        return completed;
    }

}
